package com.hslxy.niukewang.config;

import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.service.UserService;
import com.hslxy.niukewang.util.CommunityUtil;
import com.hslxy.niukewang.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements Constant {
    @Autowired
    private UserService userService;

    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
//        忽略静态资源
        webSecurity.ignoring().antMatchers("/resources/**");
    }



//    授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {

//        授权配置
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/diccuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                ).hasAnyAuthority(AUTHORITY_USER, AUTHORITY_ADMIN, AUTHORITY_MODERATOR)
                .antMatchers(
                        "/discuss/delete",
                        "/data/**"
                ).hasAnyAuthority(AUTHORITY_ADMIN)
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                ).hasAnyAuthority(AUTHORITY_MODERATOR)

                .anyRequest().permitAll()
                .and().csrf().disable();

//        权限不够
        http.exceptionHandling()
//                没有登录时
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        String header = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(header)){
                            // 这是异步请求
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登录"));
                        }else{
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
//                    没有处理异常
                }).accessDeniedHandler(new AccessDeniedHandler() {
                        @Override
                        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                            String header = request.getHeader("x-requested-with");
                            if ("XMLHttpRequest".equals(header)){
                                // 这是异步请求
                                response.setContentType("application/plain;charset=utf-8");
                                PrintWriter writer = response.getWriter();
                                writer.write(CommunityUtil.getJSONString(403, "你没权限访问此功能"));
                            }else{
                                response.sendRedirect(request.getContextPath() + "/denied");
                            }
                        }
                    });

//        退出相关配置
        http.logout().logoutUrl("/securitylogout");


    }
}
